package com.drinks.yiniang.ui.activity.user.order;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.order.OrdeConfirmAdapter;
import com.drinks.yiniang.common.help.PayManager;
import com.drinks.yiniang.common.listener.OnLocationChangesListener;
import com.drinks.yiniang.common.location.MyLocationManager;
import com.drinks.yiniang.entity.event.PayWXEventBus;
import com.drinks.yiniang.entity.event.ShopCartEvent;
import com.drinks.yiniang.entity.pay.AliPayJson;
import com.drinks.yiniang.entity.pay.WeiXinPayJson;
import com.drinks.yiniang.entity.shop.ShopJson;
import com.drinks.yiniang.entity.user.UserSetJson;
import com.drinks.yiniang.entity.user.address.DeliverAddressJson;
import com.drinks.yiniang.entity.user.order.OrderConfirmJson;
import com.drinks.yiniang.entity.user.order.OrderSubmitJson;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.common.WebActivity;
import com.drinks.yiniang.ui.activity.shop.ShopListActivity;
import com.drinks.yiniang.ui.activity.user.address.DeliverAddressActivity;
import com.drinks.yiniang.ui.widget.dialog.CouponSelectorDialog;
import com.drinks.yiniang.ui.widget.dialog.PayDialog;
import com.drinks.yiniang.ui.widget.dialog.PayPasswordDialog;
import com.drinks.yiniang.ui.widget.layout.OrderConfirmBottomLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.layout.TextEditLayout;
import com.hansen.library.ui.widget.layout.TextTextArrowLayout;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单确认
 * <p>
 * Created by han on 2019/11/10
 */
public class OrderConfirmActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        PayDialog.OnPayListener, PayManager.PayResultListener, CouponSelectorDialog.OnCouponChooseListener,
        OnLocationChangesListener {

    private static final int REQ_SELECT_ADDRESS_CODE = 0x01;//选择地址
    private static final int REQ_SELECT_SHOP_CODE = 0x02;//选择门店

    //nav
    private NavigationBarLayout nav_bar_order_confirm;
    //recycler
    private BaseRecyclerView rcv_order_confirm;
    //bottom
    private OrderConfirmBottomLayout ll_order_confirm_bottom;

    //header view
    //自提
    private TextView tv_order_confirm_choose_left;
    //外送
    private TextView tv_order_confirm_choose_right;
    //收货人
    private TextView tv_order_confirm_username;
    //手机号
    private TextView tv_order_confirm_mobile;
    //详细地址
    private TextView tv_order_confirm_address;
    //添加地址
    private TextView tv_order_confirm_add_address;
    //arrow
    private ImageView iv_order_confirm_arrow;

    //footer view
    //商品价格
    private TextTextArrowLayout ll_order_confirm_money;
    //运费
    private TextTextArrowLayout ll_order_confirm_deliver_fee;
    //订单总价
    private TextTextArrowLayout ll_order_confirm_total;
    //优惠券
    private TextTextArrowLayout ll_order_confirm_coupon;
    //备注
    private TextEditLayout ll_order_confirm_remark;
    //支付协议
    private TextView tv_order_confirm_pay_agreement;

    private OrdeConfirmAdapter mOrdeConfirmAdapter;

    private PayDialog mPayDialog;

    private PayManager mPayManager;
    private MyLocationManager mLocationManager;

    //当前支付方式
    private int mCurrentPayType = 0;
    //数量
    private int mNum;

    //经纬度
    private double mLng, mLat;

    //购物车id(购物车id存在说明是从购物车进入)
    private String mCartId;
    //商品id
    private String mGoodsId;
    //sku id
    private String mSkuId;
    //地址id
    private String mAddressId;
    //是否自提, 0-否, 1-是
    private String mSeflGet;
    //自提的门店id
    private String mShopId;
    //优惠券id
    private String mCounonId;
    //订单id
    //private String mOrderId;
    //支付id
    private String mPayId;
    //支付订单号
    private String mPayOrderNum;
    //支付获取的积分
    private String mGainPoints;

    private StringBuilder mBuilder;

    //是否同意支付协议
    private boolean isAgreePayment;
    //配送地址
    private DeliverAddressJson.DeliverAddressData mDeliverAddressData;
    //门店地址
    private ShopJson.ShopList mShopAddress;

    @Override
    protected void initView() {
        nav_bar_order_confirm = findViewById(R.id.nav_bar_order_confirm);

        rcv_order_confirm = findViewById(R.id.rcv_order_confirm);

        ll_order_confirm_bottom = findViewById(R.id.ll_order_confirm_bottom);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        if (getIntent() != null) {
            mCartId = getIntent().getStringExtra(Constants.KeyId);
            mGoodsId = getIntent().getStringExtra(Constants.KeyGoodsId);
            mSkuId = getIntent().getStringExtra(Constants.KeySkuId);
            mNum = getIntent().getIntExtra(Constants.KeyNubmer, 1);
        }

        mPayManager = new PayManager(this);
        mLocationManager = MyLocationManager.getInstance(mContext);

        initAdapter();
        setDeliverWay(Constants.TYPE_DELIVER_WAY_OUT_GOING);
        setPayAgreementData();
        getOrderConfirmGoods();
        setAddressData(mDeliverAddressData);
        getAddressList();

        //开始定位
        mLocationManager.initLocation();
        mLocationManager.startLocation();
    }

    private void initAdapter() {
        rcv_order_confirm.setLayoutManager(new LinearLayoutManager(mContext));

        mOrdeConfirmAdapter = new OrdeConfirmAdapter(mContext, new ArrayList<OrderConfirmJson.OrderConfirmGoods>());
        mOrdeConfirmAdapter.addHeaderView(getHeaderView());
        mOrdeConfirmAdapter.addHeaderView(getHeaderAddressView());
        mOrdeConfirmAdapter.addFooterView(getFooterView());
        mOrdeConfirmAdapter.setHeaderAndEmpty(true);
        mOrdeConfirmAdapter.setCommonEmpty(getLayoutInflater(), rcv_order_confirm);
        mOrdeConfirmAdapter.bindToRecyclerView(rcv_order_confirm);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_order_confirm_choose_deliver, (ViewGroup) rcv_order_confirm.getParent(), false);

        tv_order_confirm_choose_left = mHeaderView.findViewById(R.id.tv_order_confirm_choose_left);
        tv_order_confirm_choose_right = mHeaderView.findViewById(R.id.tv_order_confirm_choose_right);

        tv_order_confirm_choose_left.setOnClickListener(this);
        tv_order_confirm_choose_right.setOnClickListener(this);

        return mHeaderView;
    }

    //获取header
    private View getHeaderAddressView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_order_confirm, (ViewGroup) rcv_order_confirm.getParent(), false);

        tv_order_confirm_username = mHeaderView.findViewById(R.id.tv_order_confirm_username);
        tv_order_confirm_mobile = mHeaderView.findViewById(R.id.tv_order_confirm_mobile);
        tv_order_confirm_address = mHeaderView.findViewById(R.id.tv_order_confirm_address);
        tv_order_confirm_add_address = mHeaderView.findViewById(R.id.tv_order_confirm_add_address);

        iv_order_confirm_arrow = mHeaderView.findViewById(R.id.iv_order_confirm_arrow);

        tv_order_confirm_username.setOnClickListener(this);
        tv_order_confirm_mobile.setOnClickListener(this);
        tv_order_confirm_address.setOnClickListener(this);
        tv_order_confirm_add_address.setOnClickListener(this);

        iv_order_confirm_arrow.setOnClickListener(this);

        return mHeaderView;
    }

    //获取header
    private View getFooterView() {
        View mFooterView = getLayoutInflater().inflate(R.layout.footer_order_confirm, (ViewGroup) rcv_order_confirm.getParent(), false);

        ll_order_confirm_money = mFooterView.findViewById(R.id.ll_order_confirm_money);
        ll_order_confirm_deliver_fee = mFooterView.findViewById(R.id.ll_order_confirm_deliver_fee);
        ll_order_confirm_total = mFooterView.findViewById(R.id.ll_order_confirm_total);
        ll_order_confirm_coupon = mFooterView.findViewById(R.id.ll_order_confirm_coupon);

        ll_order_confirm_remark = mFooterView.findViewById(R.id.ll_order_confirm_remark);

        tv_order_confirm_pay_agreement = mFooterView.findViewById(R.id.tv_order_confirm_pay_agreement);

        ll_order_confirm_coupon.setOnClickListener(this);
        tv_order_confirm_pay_agreement.setOnClickListener(this);

        return mFooterView;
    }

    @Override
    protected void initListener() {
        nav_bar_order_confirm.setOnNavgationBarClickListener(this);
        ll_order_confirm_bottom.setButtonClickListener(this);
        mPayManager.setPayResultListener(this);
        mLocationManager.setLocationChangeListener(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void widgetClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.tv_order_confirm_choose_left://自提
                setShopData(mShopAddress);
                setDeliverWay(Constants.TYPE_DELIVER_WAY_SELF_GET);
                break;
            case R.id.tv_order_confirm_choose_right://外送
                setAddressData(mDeliverAddressData);
                setDeliverWay(Constants.TYPE_DELIVER_WAY_OUT_GOING);
                break;
            case R.id.tv_order_confirm_username://地址
            case R.id.tv_order_confirm_mobile:
            case R.id.tv_order_confirm_address:
            case R.id.tv_order_confirm_add_address:
            case R.id.iv_order_confirm_arrow:
                if (Constants.TYPE_DELIVER_WAY_SELF_GET.equals(mSeflGet)) {
                    mIntent = new Intent(mContext, ShopListActivity.class);
                    mIntent.putExtra(Constants.KeyChoose, true);
                    startActivityForResult(mIntent, REQ_SELECT_SHOP_CODE);
                } else {
                    mIntent = new Intent(mContext, DeliverAddressActivity.class);
                    mIntent.putExtra(Constants.KeyChoose, true);
                    startActivityForResult(mIntent, REQ_SELECT_ADDRESS_CODE);
                }
                break;
            case R.id.ll_order_confirm_coupon://选择优惠券
                if (Constants.TYPE_DELIVER_WAY_SELF_GET.equals(mSeflGet)) {//自提
                    if (StringUtils.isEmpty(mShopId)) {
                        ToastUtils.showShort(getString(R.string.text_select_shop));
                        return;
                    }
                }

                CouponSelectorDialog dialog = CouponSelectorDialog.newInstance(mShopId, ll_order_confirm_bottom.getTotalMoney());
                dialog.show(getSupportFragmentManager(), Constants.TAG_COUPON_LIST_DIALOG);
                break;
            case R.id.tv_order_confirm_pay_agreement://支付协议
                isAgreePayment = !isAgreePayment;
                tv_order_confirm_pay_agreement.setCompoundDrawablesWithIntrinsicBounds(isAgreePayment ? R.mipmap.icon_choose_p : R.mipmap.icon_choose_n, 0, 0, 0);
                break;
            case R.id.btn_common_commit://提交订单
                submitOrderOneGoods();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_order_confirm;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.RESULT_CODE_NORMAL && data != null) {
            switch (requestCode) {
                case REQ_SELECT_ADDRESS_CODE://地址
                    setAddressData((DeliverAddressJson.DeliverAddressData) data.getSerializableExtra(Constants.KeyObject));
                    break;
                case REQ_SELECT_SHOP_CODE://门店
                    setShopData((ShopJson.ShopList) data.getSerializableExtra(Constants.KeyObject));
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onCouponChooseClick(String code, String value) {
        mCounonId = code;
        ll_order_confirm_coupon.setArrowText("¥" + StringUtils.getNullEmptyConvert__(value));
        ll_order_confirm_bottom.updateTotalText(ArithmeticUtil.subScaleAmount(ll_order_confirm_bottom.getTotalMoney(), value));
    }

    @Override
    public void onPayClick(int payType) {
        switch (payType) {
            case PayManager.PAY_CHANNEL_ALIPAY://支付宝支付
                mCurrentPayType = PayManager.PAY_CHANNEL_ALIPAY;
                doPayByAliPay();
                break;
            case PayManager.PAY_CHANNEL_WX://微信支付
                mCurrentPayType = PayManager.PAY_CHANNEL_WX;
                doPayByWeiXinPay();
                break;
            case PayManager.PAY_CHANNEL_WALLET://钱包支付
                mCurrentPayType = PayManager.PAY_CHANNEL_WALLET;
                doPayByWalletPay();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPayDismiss() {

    }

    @Override
    public void onPayClose() {
        if (!StringUtils.isEmpty(mPayId)) {
            setPayResult(false, getString(R.string.text_pay_cancel));
        }
    }

    @Override
    public void onPaySuccess(String msg) {
        setPayResult(true, "");
    }

    @Override
    public void onPayFail(String errCode, String errMsg) {
        setPayResult(false, errMsg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PayWXEventBus event) {
        if (PayWXEventBus.PAY_STATUS_SUCCESS == event.getPayStatus()) {//支付成功
            //发送刷新首页达人信息event
            if (PayManager.PAY_TYPE_BUY_GOODS_PAY.equals(event.getPayPage())) {
                setPayResult(true, "");
            }
        } else {
            setPayResult(false, getString(R.string.text_pay_cancel));
        }
    }

    //显示支付dialog
    private void showPayDialog(OrderSubmitJson.OrderSubmitData data) {
        mPayOrderNum = data.getPay_order_no();
        //mOrderId = data.getId();
        mPayId = data.getId();
        mGainPoints = data.getGet_points();

        mPayDialog = PayDialog.newInstance();
        mPayDialog.show(getSupportFragmentManager(), Constants.TAG_PAY_DIALOG);
    }

    //支付成功
    private void setPayResult(boolean isPaySuccess, String msg) {
        if(mPayDialog != null && mPayDialog.getDialog() != null && mPayDialog.getDialog().isShowing()) {
            mPayDialog.dismiss();
        }
        Intent intent = new Intent(mContext, OrderPayResultActivity.class);
        //intent.putExtra(Constants.KeyOrderId, mOrderId);
        intent.putExtra(Constants.KeyBoolen, isPaySuccess);
        intent.putExtra(Constants.KeyTextContents, msg);
        intent.putExtra(Constants.KeyTotal, mGainPoints);
        startActivity(intent);

        finish();
    }

    //支付宝支付
    private void doPayByAliPay() {
        showLoadingDialog();

        OrderApiIO.getInstance().doPayByAliPay(mPayOrderNum, new APIRequestCallback<AliPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AliPayJson res) {
                mPayManager.slingAiPay(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //微信支付
    private void doPayByWeiXinPay() {
        showLoadingDialog();

        OrderApiIO.getInstance().doPayByWeiXin(mPayOrderNum, new APIRequestCallback<WeiXinPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(WeiXinPayJson res) {
                mPayManager.slingWXPay(res.getData(), PayManager.PAY_TYPE_BUY_GOODS_PAY);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //钱包支付
    private void doPayByWalletPay() {
        showLoadingDialog();

        OrderApiIO.getInstance().doPayByWallet(mPayOrderNum, new APIRequestCallback<AliPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AliPayJson res) {
                setPayResult(true, "");
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //提交单个商品订单
    private void submitOrderOneGoods() {
        if (!StringUtils.isEmpty(mCartId)) {//提交多个商品的订单
            submitOrderMoreGoods();
            return;
        }

        if (StringUtils.isEmpty(mGoodsId)) {
            ToastUtils.showShort(getString(R.string.text_the_goods_does_not_exist));
            return;
        }

        if (Constants.TYPE_DELIVER_WAY_SELF_GET.equals(mSeflGet)) {//自提
            if (StringUtils.isEmpty(mShopId)) {
                ToastUtils.showShort(getString(R.string.text_select_shop));
                return;
            }
        } else {
            if (StringUtils.isEmpty(mAddressId)) {
                ToastUtils.showShort(getString(R.string.text_select_deliver_address));
                return;
            }
        }

        if (mNum <= 0) {
            ToastUtils.showShort(getString(R.string.text_goods_num_mini_value));
            return;
        }

        if (!isAgreePayment) {
            ToastUtils.showShort(R.string.text_read_and_agree_pay_agreement);
            return;
        }

        showLoadingDialog();

        String mark = ll_order_confirm_remark.getEditText();
        String lngLat = mLat != 0 && mLng != 0 ? mLng + "," + mLat : "";

        OrderApiIO.getInstance().submitOrderOneGoods(mGoodsId, mSkuId, mNum, lngLat, mAddressId, mSeflGet,
                mShopId, mCounonId, mark, new APIRequestCallback<OrderSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(OrderSubmitJson res) {
                        showPayDialog(res.getData());
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //提交多个商品订单
    private void submitOrderMoreGoods() {
        if (StringUtils.isEmpty(mAddressId)) {
            ToastUtils.showShort(getString(R.string.text_select_deliver_address));

            return;
        }

        showLoadingDialog();

        String mark = ll_order_confirm_remark.getEditText();
        String lngLat = mLat != 0 && mLng != 0 ? mLng + "," + mLat : "";

        OrderApiIO.getInstance().submitOrderMoreGoods(mCartId, lngLat, mAddressId, mSeflGet,
                mShopId, mCounonId, mark, new APIRequestCallback<OrderSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(OrderSubmitJson res) {
                        //更新购物车
                        EventBus.getDefault().post(new ShopCartEvent());
                        showPayDialog(res.getData());
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    //获取确认订单信息
    private void getOrderConfirmGoods() {
        if (!StringUtils.isEmpty(mCartId)) {
            getCartOrderConfirmGoods();
            return;
        }

        if (StringUtils.isEmpty(mGoodsId)) {
            ToastUtils.showShort(getString(R.string.text_the_goods_does_not_exist));
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().getOrderConfirmGoods(mGoodsId, mSkuId, mNum, new APIRequestCallback<OrderConfirmJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderConfirmJson res) {
                if (mOrdeConfirmAdapter == null) {
                    return;
                }
                mOrdeConfirmAdapter.getData().clear();
                mOrdeConfirmAdapter.addData(res.getData().getGoods());
                mOrdeConfirmAdapter.loadMoreEnd();

                setOrderData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mOrdeConfirmAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取(购物车)确认订单信息
    private void getCartOrderConfirmGoods() {
        showLoadingDialog();

        OrderApiIO.getInstance().getOrderConfirmCartGoods(mCartId, new APIRequestCallback<OrderConfirmJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderConfirmJson res) {
                if (mOrdeConfirmAdapter == null) {
                    return;
                }
                mOrdeConfirmAdapter.getData().clear();
                mOrdeConfirmAdapter.addData(res.getData().getGoods_list());
                mOrdeConfirmAdapter.loadMoreEnd();

                setOrderData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mOrdeConfirmAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //设置商品订单信息
    private void setOrderData(OrderConfirmJson.OrderConfirmData data) {
        if (data == null) {
            return;
        }

        mNum = data.getGoods() != null ? StringUtils.getNullEmptyConvertIntOne(data.getGoods().getNum()) : 1;

        //商品价格
        mBuilder = new StringBuilder("¥");
        mBuilder.append(StringUtils.getNullEmptyConvertZeroPrice(data.getTotal_price()));
        ll_order_confirm_money.setArrowText(mBuilder.toString());
        //运费
        mBuilder = new StringBuilder("¥");
        mBuilder.append(StringUtils.getNullEmptyConvertZeroPrice(data.getPostage()));
        ll_order_confirm_deliver_fee.setArrowText(mBuilder.toString());
        //订单总价
        mBuilder = new StringBuilder("¥");
        mBuilder.append(StringUtils.getNullEmptyConvertZeroPrice(data.getOrder_price()));
        ll_order_confirm_total.setArrowText(mBuilder.toString());

        //设置总的数据
        ll_order_confirm_bottom.setTotalMoney(data.getTotal_price());
        ll_order_confirm_bottom.setTotalText(mOrdeConfirmAdapter.getData().size(), data.getTotal_price(), data.getPostage());
    }

    //获取地址列表
    private void getAddressList() {
        UserApiIO.getInstance().getDeliverAddressList(new APIRequestCallback<DeliverAddressJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(DeliverAddressJson res) {
                if (CommonUtils.isEmptyList(res.getData())) {
                    return;
                }

                setAddressData(res.getData().get(0));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //设置收货地址信息
    private void setAddressData(DeliverAddressJson.DeliverAddressData data) {
        mShopId = null;
        mAddressId = null;
        mDeliverAddressData = data;

        if (data == null) {
            tv_order_confirm_username.setText("");
            tv_order_confirm_mobile.setText("");
            tv_order_confirm_address.setText("");

            iv_order_confirm_arrow.setVisibility(View.INVISIBLE);

            tv_order_confirm_add_address.setVisibility(View.VISIBLE);
            tv_order_confirm_add_address.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_add_bank, 0, 0, 0);
            tv_order_confirm_add_address.setText(R.string.text_add_deliver_address);
            return;
        }

        tv_order_confirm_add_address.setVisibility(View.GONE);

        iv_order_confirm_arrow.setVisibility(View.VISIBLE);

        //收货人
        mBuilder = new StringBuilder();
        mBuilder.append(getString(R.string.text_receiver_colon));
        mBuilder.append(StringUtils.getNullEmptyConvert__(data.getReal_name()));
        tv_order_confirm_username.setText(mBuilder);
        //手机号
        tv_order_confirm_mobile.setText(data.getMobile());
        //地址
        String province = data.getRegion_province() != null ? data.getRegion_province().getRegion_name() : "";
        String city = data.getRegion_city() != null ? data.getRegion_city().getRegion_name() + " " : "";
        String district = data.getRegion_district() != null ? data.getRegion_district().getRegion_name() + " " : "";

        mBuilder = new StringBuilder();
        mBuilder.append(getString(R.string.text_deliver_address_colon));
        mBuilder.append(province != null ? province + " " : "");
        mBuilder.append(province != null ? province.equals(city) ? "" : city != null ? city + " " : "" : city != null ? city + " " : "");
        mBuilder.append(district != null ? district + " " : "");
        mBuilder.append(StringUtils.getNullEmptyConvert__(data.getAddress()));
        tv_order_confirm_address.setText(mBuilder);

        //地址id
        mAddressId = data.getId();
    }

    //设置门店信息
    private void setShopData(ShopJson.ShopList data) {
        mAddressId = null;
        mShopId = null;
        mShopAddress = data;

        if (data == null) {
            tv_order_confirm_username.setText("");
            tv_order_confirm_mobile.setText("");
            tv_order_confirm_address.setText("");

            iv_order_confirm_arrow.setVisibility(View.INVISIBLE);

            tv_order_confirm_add_address.setVisibility(View.VISIBLE);
            tv_order_confirm_add_address.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_add_bank, 0, 0, 0);
            tv_order_confirm_add_address.setText(R.string.text_select_shop_address);
            return;
        }

        tv_order_confirm_add_address.setVisibility(View.GONE);

        iv_order_confirm_arrow.setVisibility(View.VISIBLE);

        //门店地址
        mBuilder = new StringBuilder();
        mBuilder.append(getString(R.string.text_shop_address_colon));
        mBuilder.append(StringUtils.getNullEmptyConvert__(data.getName()));
        tv_order_confirm_username.setText(mBuilder);
        //手机号
        tv_order_confirm_mobile.setText("");
        //地址
        tv_order_confirm_address.setText(data.getAddress());

        //地址id
        mShopId = data.getId();
    }

    //设置支付协议数据和点击事件
    private void setPayAgreementData() {
        isAgreePayment = true;

        SpannableString builder = new SpannableString(getString(R.string.text_i_read_and_agree_pay_agreement));
        int end = builder.length();
        builder.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(Constants.KeyType, WebActivity.WEB_TYPE_PAY_AGREEMENT);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                /**set textColor**/
                ds.setColor(ContextCompat.getColor(mContext, R.color.color_3d6bd8));
                /**Remove the underline**/
                ds.setUnderlineText(false);
            }
        }, 7, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        tv_order_confirm_pay_agreement.setHighlightColor(Color.TRANSPARENT);
        tv_order_confirm_pay_agreement.setMovementMethod(LinkMovementMethod.getInstance());
        tv_order_confirm_pay_agreement.setText(builder);
    }

    //设置配送方式
    private void setDeliverWay(@NonNull String deliverWay) {
        if (deliverWay == null || mSeflGet == null) {//初始配送方式
            mSeflGet = Constants.TYPE_DELIVER_WAY_OUT_GOING;

            tv_order_confirm_choose_left.setSelected(false);
            tv_order_confirm_choose_right.setSelected(true);
        } else {
            if (mSeflGet.equals(deliverWay)) {
                return;
            }

            mSeflGet = deliverWay;

            if (Constants.TYPE_DELIVER_WAY_SELF_GET.equals(mSeflGet)) {//自提
                tv_order_confirm_choose_left.setSelected(true);
                tv_order_confirm_choose_right.setSelected(false);
            } else {
                tv_order_confirm_choose_left.setSelected(false);
                tv_order_confirm_choose_right.setSelected(true);
            }
        }
    }

    @Override
    public void locationChange(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mLng = aMapLocation.getLongitude();
                mLat = aMapLocation.getLatitude();
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        mCurrentPayType = 0;
        if (mPayManager != null) {
            mPayManager.destroyPayRegister();
        }
        mLocationManager.stopLocation();
        mLocationManager.destroyLocation();
        mPayDialog = null;
        super.onDestroy();
    }
}
